<!--
* description: 价格策略维护
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
      :dynamic-api-style="'restful'"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :existing-repair-type="existingRepairType"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { exportExcel } from '@/utils/getTimeString.js'
import api from '@/api/pa/apiBaseData'
import Vue from 'vue'

export default {
  name: 'PriceStrategyMaintenance',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editRowData: {},
      // 网格查询API配置对象
      apiConfig: api.queryPriceStrategyPage,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'add',
          clickEvent: () => {
            this.editRowData = {}
            // this.existingRepairType = this.$refs['multipleTable'].list.map(row => row['partRepairType'])
            this.showEdit('add')
          },
          text: this.$t('sys.button.add'), // 新增
          position: 'left'
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: '导出',
          name: 'export',
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          clickEvent: () => this.handFileListChange(),
          text: '导入',
          name: 'import', // 按钮图标样式
          position: 'upload'
        },
        {
          compKey: 'btnKey5',
          type: 'text',
          size: 'small',
          position: 'upload',
          click: (event) => {
            this.templateDownload()
            // this.export(
            //   // api.templateDownload.APIUrl,
            //   '欠拨结案特殊备件定义模板',
            //   { dataType: 'excel' }
            // )
          }
        }
        // {
        //   compKey: 'btnKey5',
        //   type: '',
        //   size: 'small',
        //   clickEvent: () => this.download(),
        //   text: '下载模板',
        //   name: 'download',
        //   position: 'right'
        // },

      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '维修类型：',
              codeField: 'partRepairType',
              textField: 'partRepairTypeName',
              customObj: {
                api: api.queryPartRepairs
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '备件名称码：',
              codeField: 'partNameCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '总部利润率(%)：',
              codeField: 'oemProfitMarginL',
              // span: 3,
              component: () => import('@/components/org/commonInput'),
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '~(%)',
              codeField: 'oemProfitMarginH',
              // span: 3,
              component: () => import('@/components/org/commonInput'),
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '网点利润率(%)：',
              codeField: 'dlrProfitMarginL',
              // span: 3,
              component: () => import('@/components/org/commonInput'),
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey6',
              labelName: '~(%)',
              codeField: 'dlrProfitMarginH',
              // span: 3,
              component: () => import('@/components/org/commonInput'),
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '状态：',
              codeField: 'isEnable',
              component: () => import('@/components/org/isEnable/isEnableOne'),
              type: 'dropdownList',
              isMul: false,
              isMust: true
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'priceStrategyId',
              label: '价格策略ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'modifier',
              label: '修改者ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发字段ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partNameId',
              label: '备件名称码ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partRepairType',
              label: '维修类型编码',
              hidden: true,
              alwaysHidden: true
            },

            {
              prop: 'partRepairTypeName',
              label: '维修类型',
            },
            {
              prop: 'partNameValue',
              label: '备件名称码',
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  codeField: 'partNameValue',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index)
                }
              ]
            },
            // {
            //   prop: 'partName',
            //   label: '备件标准名称'
            // },
            {
              prop: 'oemProfitMargin',
              label: '总部利润率'
            },
            {
              prop: 'oemProfitMarginMin',
              label: '总部最低利润率'
            },
            {
              prop: 'dlrProfitMargin',
              label: '正常订单利润率'
            },
            {
              prop: 'dlrProfitMarginMin',
              label: '正常订单最低利润率'
            },
            // {
            //   prop: 'urgentOrderFloatingRate',
            //   label: '紧急订单浮动率'
            // },
            {
              prop: 'isEnableCn',
              label: '状态'
            },
            {
              prop: 'modifier',
              label: '最后修改人'
            },
            {
              prop: 'lastUpdatedDate',
              label: '最后修改时间'
            }
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        oemProfitMarginL: '',
        oemProfitMarginH: '',
        dlrProfitMarginL: '',
        dlrProfitMarginH: '',
        partRepairType: '',
        partNameCode: '',
        isEnable: ''
        // bigAreaId: '',
        // updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    exportExcel111() {
      exportExcel(this.formField, api.queryPriceStrategyExport.APIUrl, api.queryPriceStrategyExport.ServiceCode, '备件价格策略')
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('备件价格策略维护模板.xlsx')
      this.$requestAPI({
        apiUrl: api.queryPriceStrategyExcelTemplate.APIUrl,
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      const that = this
      const url = api.importPriceStrategy.APIUrl
      that
        .$requestUpload(url, param)
        .then(response => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            that.queryTable()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
    }
  }
}
</script>
